package cn.com.cifi.mars.util.json;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.com.cifi.mars.util.StrUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class JsonUtils {

	private static final ObjectMapper mapper = new ObjectMapper();
	  
	  public static <T> T convertJsonToBean(String jsonString, Class<T> beanType)
	  {
	    if ((StrUtils.isNotEmpty(jsonString)) && (beanType != null)) {
	      try
	      {
	        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	        return (T)mapper.readValue(jsonString, beanType);
	      }
	      catch (Exception e)
	      {
	        log.error("###### errorMsg: ", e);
	      }
	    }
	    return null;
	  }
	  
	  public static Map<String, Object> convertJsonToMap(String jsonString)
	  {
	    if (StrUtils.isNotEmpty(jsonString)) {
	      try
	      {
	        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	        return (Map)mapper.readValue(jsonString, Map.class);
	      }
	      catch (Exception e)
	      {
	        log.error("###### errorMsg: ", e);
	      }
	    }
	    return null;
	  }
	  
	  public static String convertObjectToJson(Object bean)
	  {
	    try
	    {
	      mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
	      return mapper.writeValueAsString(bean);
	    }
	    catch (JsonProcessingException e)
	    {
	      log.error("###### errorMsg: ", e);
	    }
	    return null;
	  }
	  
	  public static Collection<?> convertJsonToList(String jsonString, Class<?> collectionClass, Class<?>... elementClasses)
	  {
	    try
	    {
	      JavaType collectionType = mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
	      return (Collection)mapper.readValue(jsonString, collectionType);
	    }
	    catch (JsonParseException e)
	    {
	      log.error("###### errorMsg: ", e);
	    }
	    catch (JsonMappingException e)
	    {
	      log.error("###### errorMsg: ", e);
	    }
	    catch (IOException e)
	    {
	      log.error("###### errorMsg: ", e);
	    }
	    return null;
	  }
}
